package com.sunday.electric.ui;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sunday.common.adapter.MainFragmentPagerAdapter;
import com.sunday.common.event.EventBus;
import com.sunday.common.logger.Logger;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.ViewPager;
import com.sunday.electric.R;
import com.sunday.electric.base.BaseActivity;
import com.sunday.electric.base.BaseApplication;
import com.sunday.electric.db.MessageDB;
import com.sunday.electric.db.RecentDB;
import com.sunday.electric.entity.Member;
import com.sunday.electric.entity.Message;
import com.sunday.electric.entity.MessageItem;
import com.sunday.electric.entity.RecentItem;
import com.sunday.electric.fragment.IndexFragment;
import com.sunday.electric.fragment.MineFragment;
import com.sunday.electric.fragment.PlainFragment;
import com.sunday.electric.fragment.QRCodeFragment;
import com.sunday.electric.fragment.WorkFragment;
import com.sunday.electric.http.ApiClient;
import com.sunday.electric.service.ChatService;
import com.sunday.electric.smack.SmackImpl;
import com.sunday.electric.ui.mine.NoticeActivity;
import com.sunday.electric.ui.mine.OnLineHelpActivity;
import com.sunday.electric.ui.mine.PersonInfoActivity;
import com.sunday.electric.ui.mine.SettingActivity;
import com.sunday.electric.utils.SharePerferenceUtils;

import java.net.URLDecoder;
import java.net.URLEncoder;
import org.jivesoftware.smack.chat.ChatManager;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener ,ChatService.IConnectionStatusCallback,ChatService.LoginStatusCallback,ChatService.onMessageCallback {

    @Bind(R.id.content)
    ViewPager viewPager;
    @Bind(R.id.nav_view)
    NavigationView navigationView;


    private IndexFragment fragmentIndex;
  /*  private PlainFragment fragmentCategory;
    private WorkFragment fragmentCenter;*/
    private QRCodeFragment qrcodeFragment;
    private MineFragment fragmentManage;
    private ArrayList<Fragment> fragments;
    @Bind({ R.id.main,R.id.product,R.id.center, R.id.qrcode,R.id.manage })
    List<ImageButton> tabViews;

    private int currentTab = 0;
    private DrawerLayout drawer;
    private ChatService chatService;
    public static final String LOGIN_ACTION = "com.way.action.LOGIN";

    private RecentDB mRecentDB;
    private MessageDB mMsgDB;// 保存消息的数据库

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        fragments = new ArrayList<>(3);
        fragmentIndex = new IndexFragment();
        qrcodeFragment = new QRCodeFragment();
        fragmentManage = new MineFragment();
        fragments.add(fragmentIndex);
        fragments.add(qrcodeFragment);
        fragments.add(fragmentManage);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        TextView orgName = (TextView)navigationView.getHeaderView(0).findViewById(R.id.org_name);
        TextView userName = (TextView)navigationView.getHeaderView(0).findViewById(R.id.user_name);



        Member member = SharePerferenceUtils.getIns().getOAuth();
        orgName.setText(member.getOrgName());
        userName.setText(member.getOpName()+" ("+member.getLoginName()+")");
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        tabViews.get(0).setSelected(true);
        viewPager.setAdapter(new MainFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(position==1){
                    updateTables(3);
                }else if(position==2){
                    updateTables(4);
                }else if(position==0){
                    updateTables(currentTab);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        // 消息
        mMsgDB = BaseApplication.getInstance().getMessageDB();// 发送数据库
        mRecentDB = BaseApplication.getInstance().getRecentDB();// 接收消息数据库
        startService(new Intent(this, ChatService.class));
        bindXMPPService();
    }


    private void bindXMPPService() {
        Logger.i(TAG, "[SERVICE] Unbind");
        Intent mServiceIntent = new Intent(this, ChatService.class);
        mServiceIntent.setAction(LOGIN_ACTION);
        bindService(mServiceIntent, mServiceConnection,
                Context.BIND_AUTO_CREATE);
    }

    ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ChatService.ChatBinder ibinder = (ChatService.ChatBinder)service;
            MainActivity.this.chatService = ibinder.getService();
            chatService.registerConnectionStatusCallback(MainActivity.this);
            chatService.setLoginStatusCallback(MainActivity.this);
            chatService.setOnMessageCallback(MainActivity.this);
            // 开始连接xmpp服务器
            chatService.Login();

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            chatService.unRegisterConnectionStatusCallback();
            chatService = null;
        }

    };

    @Override
    public void connectionStatusChanged(int connectedState, String reason) {

    }


    @Override
    public void loginSuccess() {

    }

    @Override
    public void loginFail() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast(mContext,"登录IM服务器失败");
            }
        });

    }

    @Override
    public void processMsg(org.jivesoftware.smack.packet.Message msg) {
        android.os.Message tempMsg = new android.os.Message();

        Message msgItem = new Message(MessageItem.MESSAGE_TYPE_TEXT,System.currentTimeMillis(),
                msg.getBody(),null,0);
        msgItem.setNick(msg.getFrom());
        tempMsg.obj = msgItem;
        String formId = msg.getFrom();
        String userId = msgItem.getUser_id();
        int headId = msgItem.getHead_id();
        // ===接收的额数据，如果是record语音的话，用播放展示
        MessageItem item = null;
        RecentItem recentItem = null;
        if (msgItem.getMessagetype() == MessageItem.MESSAGE_TYPE_TEXT) {
            item = new MessageItem(MessageItem.MESSAGE_TYPE_TEXT,
                    msgItem.getNick(), System.currentTimeMillis(),
                    msgItem.getMessage(), headId, true, 0,
                    msgItem.getVoiceTime());
            recentItem = new RecentItem(MessageItem.MESSAGE_TYPE_TEXT,
                    msg.getFrom(), headId, msgItem.getNick(),
                    msgItem.getMessage(), 0,
                    System.currentTimeMillis(), msgItem.getVoiceTime(),formId);

        } else if (msgItem.getMessagetype() == MessageItem.MESSAGE_TYPE_RECORD) {
            item = new MessageItem(MessageItem.MESSAGE_TYPE_RECORD,
                    msgItem.getNick(), System.currentTimeMillis(),
                    msgItem.getMessage(), headId, true, 0,
                    msgItem.getVoiceTime());
            recentItem = new RecentItem(
                    MessageItem.MESSAGE_TYPE_RECORD, userId, headId,
                    msgItem.getNick(), msgItem.getMessage(), 0,
                    System.currentTimeMillis(), msgItem.getVoiceTime(),formId);
        } else if (msgItem.getMessagetype() == MessageItem.MESSAGE_TYPE_IMG) {
            item = new MessageItem(MessageItem.MESSAGE_TYPE_IMG,
                    msgItem.getNick(), System.currentTimeMillis(),
                    msgItem.getMessage(), headId, true, 0,
                    msgItem.getVoiceTime());
            recentItem = new RecentItem(MessageItem.MESSAGE_TYPE_IMG,
                    userId, headId, msgItem.getNick(),
                    msgItem.getMessage(), 0,
                    System.currentTimeMillis(), msgItem.getVoiceTime(),formId);
        }
        mMsgDB.saveMsg(msgItem.getUser_id(), item);// 保存数据库
        mRecentDB.saveRecent(recentItem);
        EventBus.getDefault().post(recentItem);
     //   handler.sendMessage(tempMsg);
    }


    private void updateTables(int position){
        for (int i = 0; i < tabViews.size(); i++) {
            tabViews.get(i).setSelected(false);
        }
        tabViews.get(position).setSelected(true);
    }

    public void openMenu(){
        drawer.openDrawer(GravityCompat.START);
    }

    public void onTabClick(int position){
        updateTables(position);
    }

    public void openQrcode(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateTables(3);
                viewPager.setCurrentItem(1, false);
            }
        });

    }

    public void sign(String planId){
        String latitude = SharePerferenceUtils.getIns().getString(Constants.LATITUDE,"120");
        String longitude = SharePerferenceUtils.getIns().getString(Constants.LONGITUDE,"30");
        String address = URLEncoder.encode(SharePerferenceUtils.getIns().getString(Constants.LOCATION_ADDRESS, "来自火星的你"));
        String method = "updateJcPlanExcuteExcStatusToExcute"; //工作负责人签到方法

        Call<ResultDO> call = ApiClient.getIMAdapter().siginUser(latitude,longitude,
                method,planId,address);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                ResultDO resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    ToastUtils.showToast(mContext, "签到成功");
                /*    intent = new Intent(mContext, MainActivity.class);
                    startActivity(intent);
                    SharePerferenceUtils.getIns().putBoolean(Constants.IS_LOGIN, true);
                    finish();*/
                } else {
                    ToastUtils.showToast(mContext, "签到失败");
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "签到异常");
            }
        });
    }

    public void signLeader(String planId){
        String latitude = SharePerferenceUtils.getIns().getString(Constants.LATITUDE,"120");
        String longitude = SharePerferenceUtils.getIns().getString(Constants.LONGITUDE,"30");
        String address = URLEncoder.encode(SharePerferenceUtils.getIns().getString(Constants.LOCATION_ADDRESS, "当前无法获取您的位置"));
        String opId = SharePerferenceUtils.getIns().getOAuth().getOpId(); //人员Id
        String method = "updateJcPlanExcuteExcStatusForLeader"; //领导签到方法

        Call<ResultDO> call = ApiClient.getIMAdapter().siginLeader(latitude,longitude,
                method,planId,address,opId);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                ResultDO resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    ToastUtils.showToast(mContext, "签到成功");
                /*    intent = new Intent(mContext, MainActivity.class);
                    startActivity(intent);
                    SharePerferenceUtils.getIns().putBoolean(Constants.IS_LOGIN, true);
                    finish();*/
                } else {
                    ToastUtils.showToast(mContext, "签到失败");
                }
            }
            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext,"签到异常");
            }
        });
    }

    public void updatePlain(){

    }

    @OnClick(R.id.main)
    void mainPage(){
        currentTab = 0;
        updateTables(0);
        viewPager.setCurrentItem(0, false);
        fragmentIndex.getmXWalkView().getNavigationHistory().clear();
        fragmentIndex.loadIndex();
    }


    @OnClick(R.id.product)
    void category(){
        currentTab = 1;
        updateTables(1);
        viewPager.setCurrentItem(0,false);
        fragmentIndex.getmXWalkView().getNavigationHistory().clear();
        fragmentIndex.loadPlain();
    }

    @OnClick(R.id.center)
    void managment() {
        currentTab = 2;
        updateTables(2);
        viewPager.setCurrentItem(0, false);
        fragmentIndex.getmXWalkView().getNavigationHistory().clear();
        fragmentIndex.loadThird();
    }
    @OnClick(R.id.qrcode)
    void qrcode(){
        viewPager.setCurrentItem(1,false);
    }
    @OnClick(R.id.manage)
    void mine(){
        viewPager.setCurrentItem(2,false);
    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {

            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            intent = new Intent(mContext, PersonInfoActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_slideshow) {
            intent = new Intent(mContext, NoticeActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_manage) {
            intent = new Intent(mContext, SettingActivity.class);
            startActivity(intent);

        } else if (id == R.id.nav_send) {
            intent = new Intent(mContext, OnLineHelpActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (fragmentIndex.getmXWalkView() != null) {
            fragmentIndex.getmXWalkView().pauseTimers();
            fragmentIndex.getmXWalkView().onHide();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (fragmentIndex.getmXWalkView() != null) {
            fragmentIndex.getmXWalkView().resumeTimers();
            fragmentIndex.getmXWalkView().onShow();
        }
        if(chatService!=null){
            chatService.setOnMessageCallback(MainActivity.this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (fragmentIndex.getmXWalkView() != null) {
            fragmentIndex.getmXWalkView().onDestroy();
        }
        SmackImpl.getIns().loginOut();
        unbindService(mServiceConnection);
        chatService.stopSelf();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (fragmentIndex.getmXWalkView() != null) {
            fragmentIndex.getmXWalkView().onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {

        if (fragmentIndex.getmXWalkView() != null) {
            fragmentIndex.getmXWalkView().onNewIntent(intent);
        }
    }
}
